package com.cskaoyan.service;

import com.cskaoyan.bean.BasePageData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.User;
import com.cskaoyan.bean.UserExample;
import com.cskaoyan.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public BasePageData query(String username, String mobile, BaseParam param) {
        //配置分页信息 → 在执行预编译过程，会帮你拼接分页的sql语句
        PageHelper.startPage(param.getPage(), param.getLimit());

        UserExample example = new UserExample();
        //构造条件 → List<Criterion> → and方法做的事情就是构造一个Criterion的对象添加到List里
        //如果username不为null，拼接条件 and username like '%songge%'
        UserExample.Criteria criteria = example.createCriteria();
        if (username != null && !"".equals(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (mobile != null && !"".equals(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        //.andPasswordBetween("niupi","buniupi");
        //设置排序
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<User> users = userMapper.selectByExample(example);

        //分页插件 → 做分页
        //执行完查询之后，可以获得分页结果 → 用哪些数据取决于你的前端需要哪些数据
        //PageInfo中需要传入查询结果
        /*PageInfo<User> userPageInfo = new PageInfo<>(users);

        BasePageData<User> userBasePageData = new BasePageData<>();
        userBasePageData.setPage(param.getPage());
        userBasePageData.setLimit(param.getLimit());
        userBasePageData.setPages(userPageInfo.getPages());
        userBasePageData.setTotal((int) userPageInfo.getTotal());
        userBasePageData.setList(users);

        return userBasePageData;*/
        return BasePageData.ok(users);
    }
}
